import cutils from '../../js/common/core-utils.js';

$(function() {
	var vars = cutils.getUrlVars();
	var roleId = vars["roleId"];
	$("#q-role-id").val(roleId);
	initTable();
});

self.initTable = function() {
	$('#data-table').treegrid({
		url: "/" + cutils.webApp + "/role/function?roleId=" + $("#q-role-id").val() + "&_time=" + cutils.now(),
		method: 'get',
		idField: "functionId",
		treeField: "name",
		animate: true,
		fit: true,
		pagination: false,// 分页控件
		rownumbers: false,// 行号
		loadMsg: false,
		resizeHandle: 'right',
		checkbox: true,
		emptyMsg: '无数据',
		onLoadSuccess: function(row, data) {
			$('#data-table').treegrid("clearChecked");
			var options = $('#data-table').treegrid("options");
			doInitCheckNode(data, options);

			var roots = $('#data-table').treegrid("getRoots");
			doCollapse(null, roots);
		},
		onLoadError: function() {
			$(".datagrid-body").html("<div style='width: 100%; height: 50px; line-height: 50px; text-align: center;font-size: 14px;'>数据加载出错</div>");
		},
		loadFilter: function(data, parentId) {
			if (cutils.notEquals(data.status, 200)) {
				layer.msg(data.message, { icon: 3 });
				return;
			}
			return doFunctionToTree(data.data.dataList);
		},
		onCheckNode: function(row, status) {
			doChangeCheckAllBox();
		},
		columns: [[{
			field: 'name',
			title: '<div class="check-all" id="check-all-box" onclick="doTriggerCheckbox()"></div><div class="field-name">功能名称</div>',
			width: 210
		}, {
			field: 'type',
			title: '功能类型',
			align: 'center',
			width: 80,
			formatter: function(value, row, index) {
				if (value == 0) {
					return "菜单";
				}
				if (value == 1) {
					return "权限";
				}
				return "";
			}
		}, {
			field: 'url',
			title: '链接',
			width: 430,
			formatter: function(value, row, index) {
				return "<span title='" + value + "'>" + value + "</span>";
			}
		}]]
	});
}

self.doFunctionToTree = function(list) {
	$.each(list, function(i, item) {
		item.hasParent = false;
	});

	$.each(list, function(i, item) {
		item.children = [];
		$.each(list, function(i, subItem) {
			if (item.functionId == subItem.functionPId) {
				subItem.hasParent = true;
				item.children.push(subItem);
			}
		});
	});

	var treeList = [];
	$.each(list, function(i, item) {
		item.iconCls = item.icon;
		if (item.icon == null || item.icon == "") {
			item.iconCls = "fa-paper-plane-o";
		}
		item.iconCls = "fa " + item.iconCls;

		if (item.type == 1) {//权限类型图标
			item.iconCls = "fa-dot-circle-o";
		}

		if (!item.hasParent) {
			treeList.push(item);
		}
	});
	return treeList;
}

self.doTriggerCheckbox = function() {
	if ($("#check-all-box").hasClass("check-some-checked")) {
		$("#check-all-box").removeClass("check-some-checked");
	}

	var isChecked = $("#check-all-box").hasClass("check-all-checked");
	if (isChecked) {
		$("#check-all-box").removeClass("check-all-checked");
		$('#data-table').treegrid("clearChecked");
	} else {
		$("#check-all-box").addClass("check-all-checked");

		var roots = $('#data-table').treegrid("getRoots");
		var options = $('#data-table').treegrid("options");

		$.each(roots, function(i, root) {
			$('#data-table').treegrid("checkNode", root[options.idField]);
		});
	}
}

self.doChangeCheckAllBox = function() {
	var ckNodes = $('#data-table').treegrid("getCheckedNodes");

	if ($("#check-all-box").hasClass("check-some-checked")) {
		$("#check-all-box").removeClass("check-some-checked");
	}

	if ($("#check-all-box").hasClass("check-all-checked")) {
		$("#check-all-box").removeClass("check-all-checked");
	}

	if (ckNodes == null || ckNodes.length == 0) {
		return;
	}

	var roots = $('#data-table').treegrid("getRoots");

	if (doCountNodes(roots) == ckNodes.length) {
		$("#check-all-box").addClass("check-all-checked");
		return;
	}

	$("#check-all-box").addClass("check-some-checked");
}

self.doCountNodes = function(nodes) {
	var count = 0;
	$.each(nodes, function(i, node) {
		count++;
		if (node.children && node.children.length > 0) {
			count += doCountNodes(node.children);
		}
	});
	return count;
}

self.doInitCheckNode = function(nodes, options) {
	$.each(nodes, function(i, node) {
		if (cutils.isNotEmpty(node.roleId)) {
			$('#data-table').treegrid("checkNode", node[options.idField]);
			return true;//本节点被选择，则子节点也会被选择，因此结束子节点的遍历
		}

		//父节点没有选中的情况下，如果有子节点，则遍历子节点
		if (node.children && node.children.length > 0) {
			doInitCheckNode(node.children, options);
		}
	});
}

self.doSubmitHandler = function(layerFromWin, pageFromWindow) {
	var jsonData = {
		roleId: $("#q-role-id").val(),
		functions: []
	}

	var ckNodes = $('#data-table').treegrid("getCheckedNodes");
	$.each(ckNodes, function(i, node) {
		jsonData.functions.push(node.functionId);
	});

	$.ajax({
		type: "post",
		url: "/" + cutils.webApp + "/role/function?_time=" + cutils.now(),
		data: JSON.stringify(jsonData),
		dataType: 'json',
		success: function(result) {
			if (cutils.equals(result.status, 200)) {
				layerFromWin.layer.msg(result.message, { icon: 1, time: 1000 });
				var indexFrame = layerFromWin.layer.getFrameIndex(window.name);
				layerFromWin.layer.close(indexFrame);
				return;
			}
			layerFromWin.layer.msg(result.message, { icon: 7 });
		}
	});
}

self.doCollapse = function(node, childrens) {
	var flag = true;
	$.each(childrens, function(i, item) {
		if (item.type == 0) {
			flag = false;
			doCollapse(item, $('#data-table').treegrid("getChildren", item.functionId));
		}
	});
	if (node == null) {
		return;
	}
	if (flag) {
		$('#data-table').treegrid("collapse", node.functionId);
	}
}